package com.gary.lockDemo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author peng_rui
 * @date 2022/3/14
 */

class LPrint {
    private int flag = 1;

    private final Lock lock = new ReentrantLock();

    private final Condition c1 = lock.newCondition();
    private final Condition c2 = lock.newCondition();
    private final Condition c3 = lock.newCondition();

    public void printYoung(int loop) {
        //上锁
        lock.lock();
        try {
            //判断
            while (flag != 1) {
                try {
                    c1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //干活
            System.out.println();
            System.out.print("----Young----" + loop);
            //修改标志
            flag = 2;
            //通知
            c2.signal();
        } finally {
            //解锁
            lock.unlock();
        }
    }

    public void printOld(int loop) {
        //上锁
        lock.lock();
        try {
            //判断
            while (flag != 2) {
                try {
                    c2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //干活
            System.out.println();
            System.out.print("----Old------" + loop);
            //修改标志
            flag = 3;
            //通知
            c3.signal();
        } finally {
            //解锁
            lock.unlock();
        }
    }

    public void printMeta(int loop) {
        //上锁
        lock.lock();
        try {
            //判断
            while (flag != 3) {
                try {
                    c3.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //干活
            System.out.println();
            System.out.print("----Meta-----" + loop);
            //修改标志
            flag = 1;
            //通知
            c1.signal();
        } finally {
            //解锁
            lock.unlock();
        }
    }
}
public class LLoopPrint {

    public static void main(String[] args) {
        LPrint lPrint = new LPrint();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                lPrint.printYoung(i);
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                lPrint.printOld(i);
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                lPrint.printMeta(i);
            }
        }, "CC").start();
    }
}
